package com.jsmtr.rms.controller.DoZZCJ;

import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.IDoGXService;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.utils.EnumTools;
import com.jsmtr.rms.utils.StringTools;
import jxl.Sheet;
import jxl.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;


@Controller
@RequestMapping("/Do/ZZCJImport")
public class DoZZCJImportController {

    @Resource
    private IUtilService utilService;

    @Resource
    private IDoGXService doGXService;


    //[start] 查询毕业生信息

    //首页
    @RequestMapping("/")
    public String Index(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            String pid = request.getParameter("pid").trim();
            String fid = request.getParameter("fid").trim();
            String deptcode = request.getParameter("deptcode").trim();

            model.addAttribute("pid", pid);
            model.addAttribute("fid", fid);
            model.addAttribute("deptcode", deptcode);
            //招聘岗位
            List<ProjectInfoJobs> projectJobs=utilService.getProjectJobs(pid);
            model.addAttribute("jobs",projectJobs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/ZZCampusSpring/Import/index";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getusers")
    public void getusers(HttpServletRequest request, HttpServletResponse response, HRGXUser user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String flowid = request.getParameter("flowid").trim();

            Map<String, Object> map = doGXService.getUsers(page, perpage, user);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 0;
                for (HRGXUser _user : (List<HRGXUser>) object) {
                    result.append("<tr><td><input type='checkbox' id='cb_" + _user.getId() + "'></td>");
                    result.append("<td>" + (perpage * (page - 1) + num + 1) + "</td>");
                    result.append("<td class='link'><a target='_blank' href='"
                            + request.getContextPath() + "/UserResume/ViewDResume?id="
                            + _user.getId() + "'>" + _user.getName()
                            + "</a></td>");
                    result.append("<td>" + _user.getGender() + "</td>");
                    result.append("<td>" + _user.getBirthday() + "</td>");
                    result.append("<td>" + _user.getZzmm() + "</td>");
                    result.append("<td>" + _user.getCode() + "</td>");
                    result.append("<td>" + _user.getSource() + "</td>");
                    result.append("<td>" + _user.getUniversity() + "</td>");
                    result.append("<td>" + _user.getMajor() + "</td>");
                    result.append("<td>" + _user.getEducation() + "</td>");
                    result.append("<td>" + _user.getBysj() + "</td>");
                    result.append("<td>" + _user.getTel() + "</td>");
                    boolean bl = _user.getFid().equals(flowid);
                    result.append("<td class='" + bl + "'><span>" + (bl == true ? "未完成" : "已完成") + "</span></td></tr>");

                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='14'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }

    }
    //[end]

    //[start] 导入毕业生信息

    @SuppressWarnings("unchecked")
    @RequestMapping(value = {"/ImportAction"}, method = RequestMethod.POST)
    public void ImportAction(@RequestParam("excel") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        try {
            String exname = StringTools.getFileExtension(file.getOriginalFilename());//扩展名（.xxx）
            if (exname.equals(".xls")) {
                String pid = request.getParameter("pid").trim();
                String fid = request.getParameter("fid").trim();
                /*判断招聘方案的合法性*/
                ProjectInfo project = doGXService.getProject(pid);
                if (project == null) {
                    utilService.printJsonResult(false, "非法访问！", "no", response);
                } else {
                    if (project.getRecruittype() == EnumTools.RecruitType.高校校园招聘.ordinal()
                            && project.getState() == EnumTools.ProjectState.已发布.ordinal()) {

                        Map<String, Object> map = getAllByExcel(request, file.getInputStream(), pid, fid);
                        if (map != null) {
                            List<HRGXUser> ulist = (List<HRGXUser>) map.get("ulist");

                            String rp = hasRepeat(ulist);
                            if (rp.equals("ok")) {
                                utilService.addList(ulist);
                                utilService.printJsonResult(true, "操作成功", "no", response);
                            } else {
                                utilService.printJsonResult(false, rp, "no", response);
                            }
                        } else {
                            utilService.printJsonResult(false, "解析Excel数据失败！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "非法访问！", "no", response);
                    }
                }
            } else {
                utilService.printJsonResult(false, "只能上传后缀为：xls的Excel文件", "no", response);
            }

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "上传失败！", "no", response);
        }

    }

    /*检查重复*/
    private String hasRepeat(List<HRGXUser> ulist) {
        HRGXUser temp = null;
        for (int i = 0; i < ulist.size() - 1; i++) {
            temp = ulist.get(i);
            for (int j = i + 1; j < ulist.size(); j++) {
                if (temp.getCode().equals(ulist.get(j).getCode())) {
                    return "身份证号：" + temp.getCode() + "重复";
                }
            }
        }
        return "ok";
    }

    /*读取Excel文件数据*/
    private Map<String, Object> getAllByExcel(HttpServletRequest request, InputStream inputStream, String pid, String fid) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();

            List<HRGXUser> ulist = new ArrayList<HRGXUser>();

            Workbook rwb = Workbook.getWorkbook(inputStream);

            Date time = new Date();

            Sheet rs = rwb.getSheet(0);//得到第一个工作表中的数据(人员信息)
            int rows = rs.getRows();//得到所有的行

            BaseUser usr = utilService.getSessionUser(request);
            ProjectInfo project = doGXService.getProject(pid);

            for (int i = 2; i < rows; i++) {
                if (rs.getCell(0, i).getContents().length() != 0) {
                    String code = rs.getCell(5, i).getContents().trim();
                    HRGXUser _user = doGXService.getUser(pid, code);
                    if (_user == null) {
                        HRGXUser users = new HRGXUser();
                        users.setId(UUID.randomUUID().toString());
                        users.setName(rs.getCell(1, i).getContents().trim());
                        users.setGender(rs.getCell(2, i).getContents().trim());
                        users.setBirthday(rs.getCell(3, i).getContents().trim());
                        users.setZzmm(rs.getCell(4, i).getContents().trim());
                        users.setCode(code);
                        users.setSource(rs.getCell(6, i).getContents().trim());
                        users.setEducation(rs.getCell(7, i).getContents().trim());
                        users.setUniversity(rs.getCell(8, i).getContents().trim());
                        users.setMajor(rs.getCell(9, i).getContents().trim());
                        users.setBysj(rs.getCell(10, i).getContents().trim());
                        users.setTel(rs.getCell(11, i).getContents().trim());
                        users.setEmail(rs.getCell(12, i).getContents().trim());
                        users.setBz(rs.getCell(13, i).getContents().trim());
                        users.setPid(pid);
                        users.setPname(project.getPname());
                        users.setFid(fid);
                        users.setAdduid(usr.getId());
                        users.setAdduname(usr.getUname());
                        users.setAdddate(time);
                        users.setDeptcode(usr.getUdept());
                        users.setDeptname(usr.getUdeptname());

                        users.setPath("/" + fid + "/");

                        users.setRstate("未投简历");
                        users.setZsstate("无背景调查结果");
                        users.setTjstate("无体检结果");
                        users.setTjmsg("未发通知");
                        users.setGwstate("未分配");
                        users.setBdstate("未报到");
                        users.setBdmsg("未发通知");
                        users.setFqstate("未放弃");

                        ulist.add(users);
                    }
                } else {
                    break;
                }
            }
            map.put("ulist", ulist);

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    //[end]

    //[start] 流程扭转到下一步

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/NextAction", method = RequestMethod.POST)
    public void NextAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");//人员信息ID
            if (ids != null) {
                String pid = request.getParameter("pid").trim();//招聘方案ID
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码
                BaseUser usr = utilService.getSessionUser(request);
                if (usr.getUdept().equals(deptcode)) {
                    //流程是否结束
                    if (utilService.FlowIsDoing(fid)) {
                        List editlist = new ArrayList();
                        List<HRGXUser> users = doGXService.getUsers(pid, ids);

                        ProjectInfoFlow nFlow = doGXService.getNextFlow(pid, deptcode, fid);

                        for (HRGXUser user : users) {
                            if (user.getFid().equals(fid)) {
                                user.setFid(nFlow.getId());
                                user.setPath(user.getPath() + nFlow.getId() + "/");
                                editlist.add(user);
                            }
                        }
                        if (editlist.size() > 0) {
                            nFlow.setState(EnumTools.PlanFlowState.进行中.ordinal());
                            editlist.add(nFlow);
                            utilService.editList(editlist);
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        } else {
                            utilService.printJsonResult(false, "当前选中的信息不能执行此操作！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "请选择人员信息！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]
}
